package top.linyuxb.lycloud.admin.config;

import cn.hutool.core.date.DateUtil;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.linyuxb.lycloud.admin.constant.StatusEnum;
import top.linyuxb.lycloud.admin.entity.BaseEntity;
import top.linyuxb.lycloud.admin.entity.LyCloudUserEntity;
import top.linyuxb.lycloud.admin.service.impl.LoginService;

import java.util.Objects;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/7/30 17:32
 * @Desc:
 */
public class CustomEntityAuditingListener {

    @PrePersist
    private void prePersist(BaseEntity entity) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        LyCloudUserEntity lyCloudUser = (LyCloudUserEntity) request.getAttribute(LoginService.LOGIN_IDENTITY);
        entity.setStatus(StatusEnum.VALID.getType());
        if (Objects.nonNull(lyCloudUser)) {
            entity.setCreatorId(lyCloudUser.getId());
            entity.setLastModifierId(lyCloudUser.getId());
        }
        entity.setCtime(DateUtil.date().toTimestamp());
        entity.setUtime(DateUtil.date().toTimestamp());
    }

    @PreUpdate
    private void preUpdate(BaseEntity entity) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        LyCloudUserEntity lyCloudUser = (LyCloudUserEntity) request.getAttribute(LoginService.LOGIN_IDENTITY);
        if (Objects.nonNull(lyCloudUser)) {
            entity.setLastModifierId(lyCloudUser.getId());
        }
        entity.setUtime(DateUtil.date().toTimestamp());
    }
}
